﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Thor.Common;

namespace Thor.Repository.Azure.Blob
{
    public class ProviderRepository : BlobRepositoryBase, IProviderRepository
    {
        #region Constructors

        public ProviderRepository(Dictionary<string, object> repositoryParameters)
            : base(repositoryParameters) { }

        #endregion

        #region IProviderRepository Members

        public void InsertFiles(List<ProviderFile> files)
        {
            DeleteFiles();

            foreach (ProviderFile file in files)
                GetContainer().GetBlobReference(file.Name).UploadFromStream(file.Stream);
        }

        public void UpdateFiles(List<ProviderFile> files)
        {
            InsertFiles(files);
        }

        public void DeleteFiles()
        {
            var container = GetContainer();

            var blobs = container.ListBlobs();

            foreach (var blob in blobs)
                container.GetBlockBlobReference(blob.Uri.AbsoluteUri).DeleteIfExists();
        }

        public List<ProviderFile> FetchFiles()
        {
            var files = new List<ProviderFile>();

            var blobs = GetContainer().ListBlobs();

            foreach (IListBlobItem blob in blobs)
            {
                if (blob is CloudBlockBlob)
                {
                    CloudBlockBlob cloudBlockBlob = blob as CloudBlockBlob;

                    ProviderFile file = new ProviderFile();

                    file.Path = blob.Uri.AbsoluteUri;
                    file.Name = GetBlobName(cloudBlockBlob);
                    file.Bytes = cloudBlockBlob.DownloadByteArray();

                    files.Add(file);
                }
            }

            return files;
        }

        private string GetBlobName(CloudBlockBlob blob)
        {
            string[] pathSplit = blob.Uri.AbsoluteUri.Split(new char[] { '/' });
            return pathSplit[pathSplit.Length - 1];
        }

        #endregion
    }
}